package logger2.filter;

import zerdlib.events.DefaultListenable;
import zerdlib.events.containers.ListenableSet;
import zerdlib.namedObject.NamedObject;

import logger2.LogRecord;
import logger2.environment.Environment;
import logger2.filter.events.FilterChangeEvent;

public abstract class Filter extends DefaultListenable implements NamedObject {
	protected String name;
	protected Environment logEnvironment;
	
	public Filter(Environment env, String name) {
		super();
		this.name = name;
		env.getFilterCatalog().add(this);
		logEnvironment = env;
	}

	public Filter(Environment env) {
		this(env, getGeneratedName(env.getFilterCatalog()));
	}
	
	protected static String getGeneratedName(ListenableSet<Filter> filterCatalog) {
		int i=1;
		while(filterCatalog.contains("Filter-"+i)) {
			i++;
		}
		return "Filter-"+i;
	}
	
	public abstract boolean accept(LogRecord record);
	
	public String getName() {
		return name;
	}
 
	public void delete() {
		logEnvironment.getFilterCatalog().remove(this);
	}
	
	public void setName(String name) {
		FilterChangeEvent ev = new FilterChangeEvent(this);
		ev.name = !this.name.equals(name);
		this.name = name;
		if(ev.name)
			fireEvent(ev);
	}
	
	public abstract <T> T acceptVisitor(FilterVisitor<T> visitor);
	
	@Override
	public String toString() {
		return name + "(" + getClass().getName() + ")";
	}
}
